/**
 * @file demo_udp.c
 * @brief 使用标准socket套接字客户端接口实现的 udp demo
 * @version 1.0
 * @date 2021-02-23
 * @copyright Copyright (c) 2021  河北骑士智能科技有限公司
 */

#include "zos_config.h"

#ifdef BOARD_USING_DEMO_UDP
#include "zos.h"



zos_task_t task_demo_udp_handle = ZOS_NULL;

zos_uint8_t udp_send_buf[50] = "This is a udp client form QS-100 module\r\n";

zos_uint8_t udp_url[50];

zos_uint32_t udp_port;

zos_uint32_t udp_send_count;

void udp_client(void *parameter)
{
    int ret;
    char *recv_data;
    struct hostent *host;
    int sock, bytes_received;
    struct sockaddr_in server_addr;
 
    /*通过函数入口参数url获得host地址（如果是域名，会做域名解析）*/
	host = (struct hostent *) gethostbyname(udp_url);
	/*创建一个socket，类型是SOCK_DGRAM，UDP类 型 */
	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
	{
		zos_printf("[demo_udp] Socket error\n");
		goto _exit;
	}
	/*初始化预连接的服务端地址*/
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(udp_port);
	server_addr.sin_addr = *((struct in_addr *)host->h_addr);
	memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
	/*总计发送udp_send_count次数据*/
	while (udp_send_count)
	{
		/*发送数据到服务远端*/
		sendto(sock, udp_send_buf, strlen(udp_send_buf), 0, (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
		/*任务休眠一段时间*/
		zos_task_delay(200);
		/*计数值减一*/
		udp_send_count --;
	}
	/*关闭这个socket*/
	closesocket(sock);

_exit:
    task_demo_udp_handle = ZOS_NULL;
    zos_task_exit();
}



int demo_udp(int argc, char **argv)
{
    int ret;
    char *recv_data;
    struct hostent *host;
    int sock, bytes_received;
    struct sockaddr_in server_addr;

    /*接收到的参数小于3个*/
    if (argc < 3)
    {
        zos_printf("Usage: demo_udp url port\r\n");
        zos_printf("Like: demo_udp 192.168.12.44 5000\r\n");
        return ZOS_ERROR;
    }

    /*判断是否有设置发送次数，如果没设置，默认发送10次*/
    if (argc > 3)
        udp_send_count = strtoul(argv[3], 0, 10);
    else
        udp_send_count = 10;

    zos_printf("[demo_udp] ip = %s  port = %s\r\n",argv[1],argv[2]);
    strncpy(udp_url,argv[1],strlen(argv[1]));
    udp_port = strtoul(argv[2], 0, 10);

	/*创建UDP任务，任务函数使用刚才获取到的IP和port信息，连接到服务器*/
    task_demo_udp_handle = zos_task_create("demo_udp",udp_client,ZOS_NULL,1024,task_Priority_Normal);
    if(task_demo_udp_handle == ZOS_NULL)
    {
        zos_printf("[demo_udp] task create failed\r\n");
    }
	return ZOS_EOK;
    
}

#include "shell.h"

SHELL_EXPORT_CMD(demo_udp,demo_udp, udp demo);

#endif






